package org.komarichin.struts2.iterceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.komarichin.Configurator;
import org.komarichin.google.IGoogleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User: Mykhaylo Komarichyn
 * Date: 27.01.2010
 * Time: 15:57:32
 */
public class AdminPermissionInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = -7971418177032401185L;

    @Autowired
    private Configurator configurator;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
//        return invocation.invoke();
        if (Boolean.valueOf(configurator.getPropValue("struts.devMode"))) {
            return invocation.invoke();
        }
        HttpServletRequest req = ServletActionContext.getRequest();
        HttpServletResponse res = ServletActionContext.getResponse();
        String fullReqPath = req.getRequestURL().toString();

        String query = StringUtils.defaultIfEmpty(req.getQueryString(), StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(query)) {
            query = "?" + query;
        }

        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
        IGoogleService googleService = (IGoogleService) appContext.getBean("googleService");
        if (googleService.isUserAdmin()) {
            return invocation.invoke();
        } else {
            if (googleService.isUserLoggedIn()) {
                throw new SecurityException("you have not permissions for this page");
            }
            res.sendRedirect(StringEscapeUtils.unescapeXml(googleService.createLoginURL(fullReqPath + query)));
        }
        return null;
    }
}
